package cn.alcatraz.pet.service.impl;

import cn.alcatraz.pet.domain.PetType;
import cn.alcatraz.pet.mapper.PetTypeMapper;
import cn.alcatraz.pet.service.IPetTypeService;
import cn.alcatraz.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author alcatraz
 * @since 2022-07-16
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> tree() {

        List<PetType> petTypes = petTypeMapper.loadAll();

        //创建集合对象放完成的树数据
        List<PetType> petTypeTree = new ArrayList<PetType>();

        //将集合数据转为map消除时间复杂度
        //Map<Long, PetType> petTypeMap = petTypeTree.stream().collect(Collectors.toMap(PetType::getId, item -> item));
        HashMap<Long, PetType> petTypeMap = new HashMap<>();
        for (PetType petType : petTypes) {
            petTypeMap.put(petType.getId(), petType);
        }

        //从所有数据中找到一级数据
        for (PetType petTypeTmp : petTypes) {
            //如果没有父级Id就是一级数据
            if(petTypeTmp.getPid() == null){
                petTypeTree.add(petTypeTmp);
            }else {
                //map集合中获取父对象将自己添加到父对象children集合
                PetType petType = petTypeMap.get(petTypeTmp.getPid());
                if (petType != null){
                    petType.getChildren().add(petTypeTmp);
                }
            }
        }

        return petTypeTree;
    }
}
